import { useRef } from 'react';
import useCreation from './useCreation';
import useUpdate from './useUpdate';

const observer = (initialVal, cb) => {
  const proxy = new Proxy(initialVal, {
    get(target, key, receiver) {
      const res = Reflect.get(target, key, receiver);
      return typeof res === 'object' ? observer(res, cb) : res;
    },
    set(target, key, val) {
      if (key.startsWith('_')) {
        console.log(`%ccan't set private variable("${key}")`, 'color: red');
        return true;
      }
      const res = Reflect.set(target, key, val);
      cb && cb();
      return res;
    },
  });
  return proxy;
};

export default initalState => {
  const ref = useRef(initalState);
  const forceUpdate = useUpdate();
  const state = useCreation(() => observer(ref.current, forceUpdate), []);

  return state;
};
